<template>
	<view class="main">
		<view :style="{ height: navBarHeight + 'px', backgroundColor: navBarBg }" class="custom-nav-bar"
			style="transition: background-color 0.3s ease;">
			<view class="user-avatar" @click="goMyPage()">
				<!-- <up-image :src="imgSrc" width="100%" mode="scaleToFill"></up-image> -->
				<!-- <uni-icons custom-prefix="iconfont" type="icon-touxiang" size="25"></uni-icons> -->
				<image :src="userPic" mode="aspectFit"></image>
			</view>
		</view>
		<view class="image-container">
			<up-image src="https://www.zxsl.zxmap.cn/zxch-app/2025/07/01/936e27e9af7b4df2a8f46b159594d022.png"
				width="100%" mode="scaleToFill"></up-image>
		</view>
		<view class="main-content">
			<view class="tools">
				<view class="tools-main" @click="gotoRecord(0)">
					<view class="tools-title">
						<view class="title-main">
							实时录音
						</view>
						<view class="title-detail">
							<view>实时收入 | 会议纪要</view>
							<view>会议总结 | 思维导图</view>
						</view>
					</view>
					<view class="tools-img">
						<image src="/static/image/maikefeng.png" mode="aspectFit" style="width: 100%;height: 100%;">
						</image>
					</view>
				</view>
				<view class="tools-main" style="background-color: #e4f1ff;width: 45%;" @click="gotoRecord(1)">
					<view class="tools-title" style="color: #565f7f;">
						<view class="title-main">
							上传文件
						</view>
						<view class="title-detail">
							<view>上传多种类别</view>
							<view>AI智能识别</view>
						</view>
					</view>
					<view class="tools-img">
						<image src="/static/image/upload_file.png" mode="aspectFit" style="width: 100%;height: 100%;">
						</image>
					</view>
				</view>
			</view>
			<view class="content-list">
				<view class="up-tabs-container"
					:style="{ position: upTabsPosition, top: upTabsTop, padding: upTabsPadding }"
					style="width: auto;display: flex;flex-direction: row;justify-content: space-between;align-items: center;">
					<view class="">
						<view class="">
							最近会议
						</view>
						<view class="gradient-line" style="width: 100%;margin-top: -13%;"></view>
					</view>
					<view class="up-tabs-more" @click="goList()">
						<view class="">
							查看全部
						</view>
						<uni-icons type="right" size="12" color="#000"></uni-icons>
					</view>
				</view>
				<view class="page-content">
					<view class="content-main" style="overflow-y: unset;">
						<view class="main-list" style="padding: 0 0 20px 0;">
							<view v-for="(value, key) in lessNewTaskList" :key="key">
								<!-- 标题部分 -->
								<view class="main-box_text">
									<text>{{ strFormatMonth(key) }} {{ getWeekday(key) }}</text>
								</view>
								<view class="">
									<uni-swipe-action>
										<uni-swipe-action-item v-for="item in value" :key="item.taskId"
											:style="item.taskStatus == 2 || item.taskStatus == 3 ? '' : 'pointer-events: none;' "
											:right-options="rightOptions" @click="bindClick($event,item)">
											<view class="" @click="showDetail(item)">
												<view class=""
													style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;">
													<view class="main-box_title">
														{{item.taskName.slice(0, -4)}}
													</view>
													<view v-if="item.taskStatus == 0" class="flex-main"
														style="flex-shrink: 0;padding-left: 15px;">
														<view class="load-box">
															<view class="load-box_line"></view>
														</view>
														<view class="load-title">
															处理中
														</view>
													</view>
													<view v-if="item.taskStatus == 1" class="flex-main"
														style="flex-shrink: 0;padding-left: 15px;">
														<!-- <view class="load-box">
															<view class="load-box_line"></view>
														</view> -->
														<view class="load-title">
															排队中
														</view>
													</view>
													<view class="flex-main" style="flex-shrink: 0;padding-left: 15px;"
														v-if="item.taskStatus == 3">
														<view class="load-title" style="color: red">
															失败
														</view>
													</view>
												</view>
												<view class="line2">{{ item.taskContent}}</view>
											</view>
										</uni-swipe-action-item>
									</uni-swipe-action>

								</view>
							</view>
							<!-- 底部加载状态提示 -->
							<view class="loading-footer_home" v-if="lessTaskList.length == 0">
								<image src="/static/image/noData.png" mode="aspectFit" style="width: 100%;">
								</image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<FileTools />
		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="upPopupVal" background-color="#fff" type='bottom' borderRadius='20px 20px 0 0 '>
				<view class="popup-content">
					<view class="upPopup-title">
						<view class="">
							更多方式
						</view>
						<uni-icons type="closeempty" size="24" color="#363636" @click="closeUpPopup"></uni-icons>
					</view>
					<view class="upPopup-tool" @click="goUpRec">
						<view class="upPopup-tool_img">
							<uni-icons type="download" size="19" color="#363636"></uni-icons>
						</view>
						<view class="upPopup-tool_content">
							<view class="" style="font-weight: unset;">
								导入文件
							</view>
							<view class="upPopup-tool_content__small">
								导入本地音视频转写成总结与思维导图
							</view>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
		<up-toast ref="uToastRef"></up-toast>
		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog" type="dialog">
				<view class="dialog-rename">
					<view class="">
						<view class="dialog-rename-title">
							重命名
						</view>
						<view class="dialog-rename-input">
							<input v-model="newRecName" type="text" name="" id="" />
						</view>
					</view>
					<view class="flex-between-mian">
						<view class="dialog-rename_btn" @click="dialogInputClose">取消</view>
						<view class="dialog-rename_btn dialog-rename_btn__left" @click="dialogInputConfirm">保存</view>
					</view>
				</view>
			</uni-popup>
		</view>
		<view>
			<uni-popup ref="alertDelDialog" type="dialog">
				<uni-popup-dialog type="info" cancelText="否" confirmText="是" title="删除" content="是否删除当前数据?"
					@confirm="delConfirm" @close="delClose"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted,
		watch,
		nextTick
	} from 'vue';
	import {
		onShow,
		onHide,
		onPageScroll
	} from '@dcloudio/uni-app'
	import {
		getToken,
		saveToken,
		removeToken
	} from '@/utils/auth';
	import {
		useAuthStore
	} from '@/store/index.js';
	import {
		listAiTask,
		delAiTask,
		updateAiTask
	} from '../../api/index.js';
	import {
		getNewDateArr,
		getLatestTwoData
	} from '@/utils/list.js'
	import FileTools from '@/components/file-tools/index.vue'
	import userPic from '@/static/image/logo1.png'
	import {
		strFormatMonth,
		getWeekday
	} from '@/utils/format.js'

	const upPopupVal = ref(null)
	const uToastRef = ref(null)
	const lessTaskList = ref([])
	const lessNewTaskList = ref([])
	const userStore = useAuthStore();
	const userId = ref(userStore.userId);
	const navBarHeight = ref(0);
	const navBarBg = ref('transparent');
	const upTabsPosition = ref('unset');
	const upTabsPadding = ref('20px 0 10px 0')
	const upTabsTop = ref('');
	let navBarBottomY = 0;
	let upTabsTopY = 0;
	const isHomePageActive = ref(false); // 是否在首页
	const rightOptions = reactive([{
		text: '重命名',
		style: {
			backgroundColor: '#007aff',
			color: '#fff',
			height: '100%' // 与 main-box 的高度一致
		}
	}, {
		text: '删除',
		style: {
			backgroundColor: '#dd524d',
			color: '#fff',
			height: '100%' // 与 main-box 的高度一致
		}
	}])
	const inputDialog = ref(null)
	const newRecName = ref('')
	const suffixName = ref('')
	const alertDelDialog = ref(null)
	const changeId = ref(null)

	const gotoRecord = (index) => {
		// goLogin()
		if (!getToken()) {
			uToastRef.value.show({
				type: 'default',
				message: '请先登录',
				title: '请先登录'
			});
			uni.navigateTo({
				url: '/pages/login'
			})
			return
		}
		if (index == 0) {
			uni.navigateTo({
				url: '/subPackages/record/index?type=home'
			})
		} else {
			uni.navigateTo({
				url: '/subPackages/upload/index'
			})
		}
	}

	const handleData = (data) => {
		if (data.info == 0) {
			upPopupVal.value.open()
		} else {
			// goLogin()
			if (!getToken()) {
				uToastRef.value.show({
					type: 'default',
					message: '请先登录',
					title: '请先登录'
				});
				uni.navigateTo({
					url: '/pages/login'
				})
				return
			}
			uni.navigateTo({
				url: '/subPackages/record/index?type=home'
			})
		}
	};

	const closeUpPopup = () => {
		upPopupVal.value.close()
	}

	const goUpRec = () => {
		// goLogin()
		if (!getToken()) {
			uToastRef.value.show({
				type: 'default',
				message: '请先登录',
				title: '请先登录'
			});
			uni.navigateTo({
				url: '/pages/login'
			})
			return
		}
		uni.navigateTo({
			url: '/subPackages/upload/index'
		})
	}

	const goLogin = () => {
		if (!getToken()) {
			uToastRef.value.show({
				type: 'default',
				message: '请先登录',
				title: '请先登录'
			});
			uni.navigateTo({
				url: '/pages/login'
			})
			return
		}
	}

	const getList = async () => {
		const res = await listAiTask({
			userId: userStore.userId
		})
		lessTaskList.value = res.data.rows
		lessNewTaskList.value = getLatestTwoData(lessTaskList.value)
	}

	const goList = () => {
		uni.switchTab({
			url: '/pages/list/index'
		})
	}

	const goMyPage = () => {
		uni.navigateTo({
			url: '/pages/my/index'
			// url: '/pages/my/test'
		})
	}

	const bindClick = async (e, item) => {
		changeId.value = item.taskId
		if (e.index == 0) {
			if (item.taskName.includes('.')) {
				let parts = item.taskName.split('.'); // ["example", "com"]
				newRecName.value = parts[0]
				suffixName.value = parts[1]
			} else {
				newRecName.value = item.taskName
				suffixName.value = ''
			}
			await nextTick();
			inputDialog.value.open();
		} else {
			alertDelDialog.value.open()
		}
	}

	const dialogInputClose = () => {
		changeId.value = null
		newRecName.value = '请输入名称'
		inputDialog.value.close()
	}

	const dialogInputConfirm = async () => {
		const {
			data
		} = await updateAiTask({
			userId: userStore.userId,
			taskId: changeId.value,
			taskName: newRecName.value + '.' + suffixName.value
		})
		if (data.code == 200) {
			uni.showToast({
				title: '修改成功',
				icon: 'none'
			});
			await getList()
			uni.$emit('refreshList', true)
			await dialogInputClose()
		} else {
			uni.showToast({
				title: '修改失败,请重试',
				icon: 'fail',
				icon: 'none'
			})
			inputDialog.value.close()
		}
	}

	const delConfirm = async () => {
		const {
			data
		} = await delAiTask(changeId.value)
		if (data.code == 200) {
			uni.showToast({
				title: '删除成功',
				icon: 'none'
			});
			await getList()
			uni.$emit('refreshList', true)
			await delClose()
		} else {
			uni.showToast({
				title: '删除失败,请重试',
				icon: 'fail',
				icon: 'none'
			})
			alertDelDialog.value.close()
		}
	}

	const delClose = () => {
		changeId.value = null
		alertDelDialog.value.close()
	}

	onPageScroll(async (e) => {
		const scrollTop = e.scrollTop;
		navBarBg.value = scrollTop >= navBarHeight.value - 20 ? '#f5f7fb' : 'transparent'
		const shouldFix = scrollTop + navBarBottomY >= upTabsTopY;
		upTabsPosition.value = shouldFix ? 'fixed' : 'unset';
		upTabsPadding.value = shouldFix ? '20px 20px 10px 20px' : '20px 0 10px 0';
		upTabsTop.value = shouldFix ? `${navBarHeight.value}px` : '';
	});

	const getElementPosition = (selector) => {
		return new Promise((resolve) => {
			uni.createSelectorQuery()
				.select(selector)
				.boundingClientRect((res) => resolve(res))
				.exec();
		});
	};

	const showDetail = (val) => {
		uni.navigateTo({
			url: `/pages/list/detail?taskId=${val.taskId}&taskName=${val.taskName}&taskMindMap=${val.taskMindMap}&taskMindXxcMap=${val.taskMindXxcMap}`
		});
	}

	// 检查 taskStatus 并设置定时器
	const intervalId = ref(null); // 让 Vue 追踪 intervalId

	// 修改后的 watch
	watch(lessTaskList, (newList) => {
		if (!isHomePageActive.value) return;

		if (newList?.some(item => item.taskStatus == "0" || item.taskStatus == "1")) {
			startPolling();
		} else {
			stopPolling();
		}
	}, {
		deep: true
	});

	// 封装轮询方法
	const startPolling = () => {
		if (!intervalId.value && isHomePageActive.value) {
			intervalId.value = setInterval(() => {
				getList();
				uni.$emit('refreshList', true)
			}, 3000);
		}
	}

	const stopPolling = () => {
		clearInterval(intervalId.value);
		intervalId.value = null;
	}

	uni.$on('stopHomeWatch', () => {
		isHomePageActive.value = false;
		clearInterval(intervalId.value);
		intervalId.value = null;
	});

	onMounted(async () => {
		isHomePageActive.value = true;
		uni.$emit('stopListWatch'); // 通知列表页面停止监听
		try {
			const res = await uni.getSystemInfo();
			// 获取状态栏高度（刘海高度）
			const statusBarHeight = res.statusBarHeight;
			// 标准导航栏高度，一般为 44px（iOS）或 48px（Android）
			const defaultNavBarHeight = res.platform === 'ios' ? 54 : 58;
			// 计算自定义导航栏的高度
			navBarHeight.value = statusBarHeight + defaultNavBarHeight;

			const navBarRect = await getElementPosition('.custom-nav-bar');
			navBarBottomY = navBarRect.bottom;

			const upTabsRect = await getElementPosition('.up-tabs-container');
			upTabsTopY = upTabsRect.top;
		} catch (error) {
			console.error('获取设备信息失败:', error);
		}
		if (getToken()) {
			await getList()
		}
	})

	onUnmounted(() => {
		isHomePageActive.value = false;
	});

	// 页面显示时监听事件
	onShow(async () => {
		uni.$on('clikTabNum', handleData);
		uni.$emit('stopListWatch'); // 通知列表页面停止监听
		isHomePageActive.value = true;
		uni.$off('refreshHomeList');
		uni.$on('refreshHomeList', (e) => {
			if (e) {
				getList()
			}
		});
		if (uni.getStorageSync('needRefreshHome')) {
			getList()
			uni.removeStorageSync('needRefreshHome');
		}
		if (lessTaskList.value?.some(item => item.taskStatus == "0" || item.taskStatus == "1")) {
			startPolling();
		}
	});

	// 页面隐藏时移除监听
	onHide(() => {
		uni.$off('clikTabNum', handleData);
		isHomePageActive.value = false;
	});
</script>

<style>
	.main {
		/* position: relative; */
		/* height: 100vh; */
		/* 铺满整个屏幕高度 */
	}

	.user-avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		overflow: hidden;
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		bottom: 0;
		left: 10px;
		background-color: #f5f7fb;
		backdrop-filter: blur(5px);
	}

	.user-avatar image {
		width: 100%;
		height: 100%;
	}

	.image-container {
		position: relative;
		z-index: 1;
	}

	.main-content {
		position: relative;
		margin-top: -60rpx;
		background-color: #f5f7fb;
		border-radius: 20px 20px 0 0;
		padding: 20px;
		z-index: 2;
		box-sizing: border-box;
		/* 添加这一行 */
		/* position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		min-height: 68vh;
		margin-top: -50px;
		border-top-left-radius: 20px;
		border-top-right-radius: 20px;
		overflow-y: auto;
		padding: 20px; */
	}

	.tools {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.tools-main {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		border-radius: 15px;
		background-color: #4f84ff;
		/* width: calc(50% - 5px); */
	}

	.tools-title {
		color: #fff;
		padding: 10px;
	}

	.title-main {
		font-weight: 700;
		padding-top: 10px;
		font-size: 19px;
	}

	.title-detail {
		font-size: 12px;
		padding: 10px 0;
		line-height: 1.5;
	}

	.tools-img {
		width: 45px;
	}

	.popup-content {
		padding: 20px;
		background-color: #f5f7fb;
		font-weight: 600;
		color: #363636;
		font-size: 18px;
	}

	.upPopup-title {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.upPopup-tool {
		background-color: #fff;
		border-radius: 20px;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 20px;
		margin-top: 20px;
	}

	.upPopup-tool_img {
		background-color: #f5f7fb;
		border-radius: 15px;
		width: 35px;
		height: 35px;
		display: grid;
		place-items: center;
	}

	.upPopup-tool_content {
		line-height: 1.5;
		margin-left: 15px;
	}

	.upPopup-tool_content__small {
		font-size: 11px;
		color: #909399;
		font-weight: unset;
		margin-top: 10px;
	}

	.up-tabs-more {
		border: 1px solid #ececec;
		background-color: #fff;
		padding: 8px;
		display: flex;
		flex-direction: row;
		align-items: center;
		font-size: 12px;
		border-radius: 5px;
	}

	.loading-footer_home {
		width: 100%;
		margin-top: 20px;
	}

	::v-deep .uni-swipe_text--center {
		width: 100%;
		min-width: 0;
		border-radius: 15px;
		border: 1px solid #ececec;
		box-sizing: border-box;
		padding: 20px 10px;
		/* box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); */
		overflow: hidden;
		word-break: break-word;
		background-color: #fff;
	}

	::v-deep .uni-swipe {
		margin-bottom: 20px;
	}

	::v-deep .uni-swipe_button-group>.uni-swipe_button:nth-child(2) {
		border-radius: 0 15px 15px 0;
	}

	::v-deep .uni-searchbar {
		padding: 10px 0;
	}
</style>